import sys
from PyQt5.QtWidgets import QWidget, QApplication
from PyQt5.QtCore import QThread, pyqtSignal, QObject
from time import sleep
import threading
from PyQt5.QtNetwork import QTcpSocket, QTcpServer, QHostAddress

class TCP_Client_Qthread_function(QObject):
    
    signal_TCP_Client_qthread_function_Init = pyqtSignal()
    signal_pushButton_Open           = pyqtSignal(object)
    signal_pushButton_Open_flag      = pyqtSignal(object)
    signal_readyRead                 = pyqtSignal(object)
    signal_send_data                 = pyqtSignal(object)
    signal_send_data_num             = pyqtSignal(object)
    
    def __init__(self, parent=None):
        super(TCP_Client_Qthread_function, self).__init__(parent)
        #开始调用网络信号
        self.state = 0 #0 未打开 1 打开 2 关闭

    def slot_pushButton_Open(self,parameter):
        print("打开TCP Client", parameter)
        if self.state == 0:
            self.tcpsocket.connectToHost(QHostAddress(parameter['ip']), int(parameter['port']))
        else:
            self.tcpsocket.close()
            self.state = 0
            self.signal_pushButton_Open_flag.emit(2)
            
    def connected(self):
        self.state = 1
        self.signal_pushButton_Open_flag.emit(1)
        
    def slot_readyRead(self):
        buf = self.tcpsocket.readAll()
        data = {}
        data['ip']   = self.tcpsocket.peerAddress().toString()
        data['port'] = self.tcpsocket.peerPort()
        data['buf']  = buf
        self.signal_readyRead.emit(data)
        # print("TCP Server收到数据", data['ip'], data['port'], data['buf'])

    def disconnected(self):
        print("断开连接")
        self.state = 0
        self.signal_pushButton_Open_flag.emit(2)

    def slot_send_data(self,parameter):
        print("TCP Client 发送数据", parameter)
        if self.state != 1:
            return
        self.tcpsocket.write(parameter['data'])
        self.signal_send_data_num.emit(len(parameter['data']))
        
        
    def TCP_Client_qthread_function_Init(self):
        self.tcpsocket = QTcpSocket()
        self.tcpsocket.connected.connect(self.connected)
        self.tcpsocket.readyRead.connect(self.slot_readyRead)
        self.tcpsocket.disconnected.connect(self.disconnected)
        